package com.dazhuang.trans;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class UserDao {

	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public JdbcTemplate getJdbcTemplate(JdbcTemplate jdbcTemplate) {
		return this.jdbcTemplate;
	}

	public int addUser(User user) {
		// TODO Auto-generated method stub
		String sql = "insert into User(username,password,money) value(?,?,?)";
		Object[] obj = new Object[] {
				user.getUsername(),
				user.getPassword(),
				user.getMoney()
		};
		int num = this.jdbcTemplate.update(sql,obj);
		return num;
	}

	public int updateUser(User user) {
		// TODO Auto-generated method stub
		String sql = "update User set username=?,password=?,money=? where id = ?";
		Object[] params = new Object[] {
				user.getUsername(),
				user.getPassword(),
				user.getMoney(),
				user.getId()
		};
		int num = this.jdbcTemplate.update(sql,params);
		return num;
	}


	public int deleteUser(int id) {
		// TODO Auto-generated method stub
		String sql = "delete from user where id=?";
		int num = this.jdbcTemplate .update(sql,id);
		return num;
	}

	public User findUserById(int id) {
		// TODO Auto-generated method stub
		String sql ="select * from user where id=?";
		RowMapper<User> rowMapper =
				new BeanPropertyRowMapper<User>(User.class);
		return this.jdbcTemplate.queryForObject(sql, rowMapper,id);
	}

	public List<User> findAllUser() {
		// TODO Auto-generated method stub
		String sql = "select * from user";
		RowMapper<User> rowMapper =
				new BeanPropertyRowMapper<User> (User.class);
		return this.jdbcTemplate.query(sql, rowMapper);
	}

//	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)
	public void transfer(String outUser, String inUser, Double money) {
		// TODO Auto-generated method stub
		String sql1 ="update User set money=money+? where username=?";
		this.jdbcTemplate.update(sql1,money,inUser);
		String sql2 ="update user set money=money-? where username=?";
		this.jdbcTemplate.update(sql2,money,outUser);
	}
	
}
